package com.yate.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yate.auth.mapper.SysMenuMapper;
import com.yate.auth.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yate.auth.service.SysRoleMenuService;
import com.yate.common.config.MenuHelper.MenuHelper;
import com.yate.common.config.exception.BusinessException;
import com.yate.model.system.SysMenu;
import com.yate.model.system.SysRoleMenu;
import com.yate.vo.system.AssginMenuVo;
import com.yate.vo.system.MetaVo;
import com.yate.vo.system.RouterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author yate
 * @since 2024-12-02
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * @Author: yate
     * @Description: 获取菜单列表
     * @param:
     * @return:
     */

    @Override
    public List<SysMenu> findNodes() {

        //查询所有菜单
        List<SysMenu> sysMenuList = baseMapper.selectList(null);

        //构建树形数据
        List<SysMenu> resultList = MenuHelper.buildTree(sysMenuList);
        return resultList;
    }

    /**
     * @Author: yate
     * @Description: 删除菜单
     * @param:
     * @return:
     */

    @Override
    public void removeMenuById(Long id) {
        //判断是否有子菜单
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getParentId, id);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(201, "该菜单存在子菜单，无法删除");
        }
        //删除菜单
        baseMapper.deleteById(id);


    }

    /**
     * @Author: yate
     * @Description:查询所有菜单和角色分配的菜单
     * @param:
     * @return:
     */
    @Override
    public List<SysMenu> findMenuByRoleId(Long roleId) {
        //1.查询所有菜单-添加条件 status=1
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getStatus, 1);
        List<SysMenu> allSysMenuList = baseMapper.selectList(queryWrapper);

        //2.根据角色id查询角色菜单关系表的菜单id
        LambdaQueryWrapper<SysRoleMenu> wrapperSysRoleMenu = new LambdaQueryWrapper<>();
        wrapperSysRoleMenu.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuService.list(wrapperSysRoleMenu);
        //3.根据菜单id查询菜单对象
        List<Long> menuIdList = sysRoleMenuList.stream().
                map(sysRoleMenu -> sysRoleMenu.getMenuId()).collect(Collectors.toList());
        //3.1把菜单id和所有菜单集合里面id进行比较，如果相同则封装
        allSysMenuList.stream().
                forEach(item -> {
                    if (menuIdList.contains(item.getId())) {
                        item.setSelect(true);
                    } else {
                        item.setSelect(false);
                    }
                });
        //4.返回规定树形显示格式的菜单列表
        List<SysMenu> sysMenuList = MenuHelper.buildTree(allSysMenuList);
        return sysMenuList;

    }

    /**
     * @Author: yate
     * @Description:角色分配菜单
     * @param:
     * @return:
     */

    @Override
    public void doAssign(AssginMenuVo assginMenuVo) {
        //1.根据角色id删除角色菜单关系表里面的数据
        LambdaQueryWrapper<SysRoleMenu> wrapperSysRoleMenu = new LambdaQueryWrapper<>();
        wrapperSysRoleMenu.eq(SysRoleMenu::getRoleId, assginMenuVo.getRoleId());
        sysRoleMenuService.remove(wrapperSysRoleMenu);
        //2.把前端传过来的菜单id数组遍历，添加到角色菜单关系表里面
        List<Long> menuIdList = assginMenuVo.getMenuIdList();
        for (Long menuId : menuIdList) {
            if (StringUtils.isEmpty(menuId)) {
                continue;
            }
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(assginMenuVo.getRoleId());
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenuService.save(sysRoleMenu);
        }

    }

    //根据用户id查询菜单列表
    @Override
    public List<RouterVo> findUserMenuListByUserId(Long userId) {
        List<SysMenu> sysMenuList = null;
        //1.判断当前用户是否是管理员，userId=1是管理员,如果是管理员，则返回所有菜单
        if (userId.longValue() == 1) {
            //查询所有菜单
            LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysMenu::getStatus, 1);
            queryWrapper.orderByAsc(SysMenu::getSortValue);
            sysMenuList = baseMapper.selectList(queryWrapper);
        } else {
            //2.如果不是管理员，则查询当前用户所拥有的角色，再查询角色所拥有的菜单
            //多表关联查询: 用户角色关系表、角色菜单关系表、菜单表
            sysMenuList = baseMapper.findMenuListByUserId(userId);
        }
        //3.把查询出来的数据列表-构建成框架要求的路由结构
        //使用菜单操作工具类构建树形结构
        List<SysMenu> sysMenuTreeList = MenuHelper.buildTree(sysMenuList);
        //构建成框架要求的路由结构
        List<RouterVo> routerList = this.buildRouter(sysMenuTreeList);

        return routerList;
    }

    //构建路由结构
    private List<RouterVo> buildRouter(List<SysMenu> menus) {
        //创建list集合，用于存储最后封装好的路由结构
        List<RouterVo> routers = new ArrayList<>();
        //把menus遍历，进行封装
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden(false);
            router.setAlwaysShow(false);
            router.setPath(getRouterPath(menu));
            router.setComponent(menu.getComponent());
            router.setMeta(new MetaVo(menu.getName(), menu.getIcon()));
            //下一层数据部分
            List<SysMenu> children = menu.getChildren();
            if (menu.getType().intValue() == 1) {
                //加载出来下面隐藏路由
                List<SysMenu> hiddenMenuList = children.stream()
                        .filter(item -> !StringUtils.isEmpty(item.getComponent()))
                        .collect(Collectors.toList());
                for (SysMenu hiddenMenu : hiddenMenuList) {
                    RouterVo hiddenRouter = new RouterVo();
                    hiddenRouter.setHidden(true);//隐藏路由
                    hiddenRouter.setAlwaysShow(false);
                    hiddenRouter.setPath(getRouterPath(hiddenMenu));
                    hiddenRouter.setComponent(hiddenMenu.getComponent());
                    hiddenRouter.setMeta(new MetaVo(hiddenMenu.getName(), hiddenMenu.getIcon()));
                    routers.add(hiddenRouter);
                }
            } else {
                if (!CollectionUtils.isEmpty(children)) {
                    if (children.size() > 0) {
                        router.setAlwaysShow(true);
                    }
                    //如果有子菜单，则递归调用
                    router.setChildren(buildRouter(children));
                }
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = "/" + menu.getPath();
        if (menu.getParentId().intValue() != 0) {
            routerPath = menu.getPath();
        }
        return routerPath;
    }

//    根据用户id获取到用户可以操作的按钮列表
    @Override
    public List<String> findUserPermsByUserId(Long userId) {
        //1.判断当前用户是否是管理员，userId=1是管理员,如果是管理员，则返回所有按钮权限
        List<SysMenu> sysMenuList = null;
        if (userId.longValue() == 1) {
            LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysMenu::getStatus, 1);
            sysMenuList = baseMapper.selectList(queryWrapper);

        }

        //2.如果不是管理员，则查询当前用户所拥有的角色，再查询角色所拥有的按钮权限
         sysMenuList = baseMapper.findMenuListByUserId(userId);
        //3.获取可以操作的按钮值的list集合，返回按钮权限列表
        List<String> permsList = sysMenuList.stream().filter(item -> item.getType().intValue() == 2)
                .map((item -> item.getPerms())).collect(Collectors.toList());
        return permsList;
    }
}
